package handlers

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"math"
	"net/http"
	"news/models"
	"news/pkg"
	"strconv"
)

type MsgData struct {
	Sum  int `json:"sum"`
	Down int `json:"down"`
	Up   int `json:"up"`
	News []models.News
}

func UserRegister(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		username := c.PostForm("username")
		password := c.PostForm("password")
		if username == "" || password == "" {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "用户名和密码不能为空",
			})
			return
		}
		user := models.User{
			Username: username,
			Password: pkg.Md5Str(password),
		}
		err := db.Create(&user).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "注册失败",
			})
			return
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code": 200,
				"msg":  "注册成功",
			})
			return
		}
	}
}
func UserLogin(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		username := c.PostForm("username")
		password := c.PostForm("password")
		var user models.User
		err := db.Where("username=?", username).First(&user).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "用户名错误",
			})
			return
		}
		if user.Password != pkg.Md5Str(password) {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "密码错误",
			})
			return
		}
		token, _ := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
		c.JSON(http.StatusOK, gin.H{
			"code":  200,
			"msg":   "登录成功",
			"token": token,
		})
		return
	}
}
func Add(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		title := c.PostForm("title")
		content := c.PostForm("content")
		news := models.News{
			Title:   title,
			Content: content,
		}
		err := db.Create(&news).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "发布失败",
			})
			return
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code": 200,
				"msg":  "发布成功",
			})
			return
		}
	}
}
func List(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
		size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
		offset := (page - 1) * size
		var count int64
		db.Model(&models.News{}).Count(&count)
		sum := int(math.Ceil(float64(count) / float64(size)))
		up := page - 1
		if up < 1 {
			up = 1
		}
		down := page + 1
		if down > sum {
			down = sum
		}
		var news []models.News
		err := db.Offset(offset).Limit(size).Find(&news).Error
		pagedata := MsgData{
			Sum:  sum,
			Down: down,
			Up:   up,
			News: news,
		}
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "分页查询失败",
			})
			return
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code": 200,
				"msg":  "分页查询成功",
				"data": pagedata,
			})
			return
		}
	}
}
